package com.zzyl.nursing.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class AgeCalculator {

    /**
     * 根据身份证号码计算年龄
     * @param idCard 身份证号码
     * @return 年龄
     */
    public static int getAgeByIdCard(String idCard) {
        // 检查身份证号码长度
        if (idCard == null || idCard.length() != 18) {
            throw new IllegalArgumentException("Invalid ID card number!");
        }

        // 提取出生日期部分
        String birthdayStr = idCard.substring(6, 14);

        // 解析出生日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date birthDate = null;
        try {
            birthDate = sdf.parse(birthdayStr);
        } catch (ParseException e) {
            throw new IllegalArgumentException("Failed to parse birthday from ID card!", e);
        }

        // 计算年龄
        Calendar birthCal = Calendar.getInstance();
        birthCal.setTime(birthDate);

        Calendar nowCal = Calendar.getInstance();
        nowCal.setTime(new Date());

        int age = nowCal.get(Calendar.YEAR) - birthCal.get(Calendar.YEAR);

        // 判断是否过了生日
        if (nowCal.get(Calendar.DAY_OF_YEAR) < birthCal.get(Calendar.DAY_OF_YEAR)) {
            age--;
        }

        return age;
    }

    public static void main(String[] args) {
        // 示例身份证号码
        String idCard = "123456199001011234";

        // 计算年龄
        int age = getAgeByIdCard(idCard);
        System.out.println("Age: " + age);
    }
}
